#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/3 15:19
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : crud.py
# @Software: PyCharm
# @FileDescription： 数据操作

from sqlalchemy.orm import Session

from apps.system.users import model, schemas
from common.Security import get_password


def get_user(db: Session, user_id: int):
    """
    获取单条用户数据
    :param db:
    :param user_id:
    :return:
    """
    return db.query(model.User).filter(model.User.id == user_id).first()


def get_user_by_username(db: Session, username: str):
    """
    根据用户名获取用户信息
    :param db:
    :param username: 用户名
    :return: 用户信息
    """
    return db.query(model.User).filter(model.User.username == username).first()


def get_user_by_email(db: Session, email: str):
    """
    获取用户邮箱
    :param db: 
    :param email: 
    :return: 
    """
    return db.query(model.User).filter(model.User.email == email).first()


def get_users(db: Session, data_scope: list, page: int = 0, size: int = 0, sort: str = "id, desc"):
    """
    获取所有用户
    :param data_scope: 登陆用户所属权限
    :param db:
    :param page: 页码
    :param size: 每页数量
    :param sort: 排序
    :return:
    """
    # 计算偏移量
    offset = page * size
    # 筛选用户
    if sort.split(",")[0] != "desc":
        if data_scope:
            return db.query(model.User).filter(model.User.dept_id.in_(data_scope)).order_by(sort.split(",")[0]).offset(
                offset).limit(
                size).all()
        else:
            return db.query(model.User).order_by(sort.split(",")[0]).offset(offset).limit(size).all()
    else:
        if data_scope:
            return db.query(model.User).filter(model.User.dept_id.in_(data_scope)).order_by(
                sort.split(",")[0].desc()).offset(offset).limit(
                size).all()
        else:
            return db.query(model.User).order_by(sort.split(",")[0].desc()).offset(offset).limit(size).all()


def create_user(db: Session, user: schemas.UserCreate):
    """
    创建用户
    :param db:
    :param user:
    :return:
    """
    # user进行哈希加密
    user.password = get_password(user.password)
    db_user = model.User(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return user
